import {CloseCircleOutlined} from '@ant-design/icons';
import {
  Button,
  Card,
  Col,
  DatePicker,
  Form,
  Input,
  Popover,
  Row,
  Select,
  Steps,
  Transfer,
  Switch,
  Table,
  Tag,
  Modal
} from 'antd';
import React, {useState} from 'react';
import difference from 'lodash/difference';
import {FooterToolbar} from '@ant-design/pro-layout';
import styles from './style.less';
import TableForm from "@/pages/warehouse/stock-material/components/TableForm";

// Customize Table Transfer
const TableTransfer = ({leftColumns, rightColumns, ...restProps}) => (
  <Transfer {...restProps} showSelectAll={false}>
    {({
        direction,
        filteredItems,
        onItemSelectAll,
        onItemSelect,
        selectedKeys: listSelectedKeys,
        disabled: listDisabled,
      }) => {
      const columns = direction === 'left' ? leftColumns : rightColumns;

      const rowSelection = {
        onSelectAll(selected, selectedRows) {
          const treeSelectedKeys = selectedRows
            .map(({processCode}) => processCode);
          const diffKeys = selected
            ? difference(treeSelectedKeys, listSelectedKeys)
            : difference(listSelectedKeys, treeSelectedKeys);
          onItemSelectAll(diffKeys, selected);
        },
        onSelect({processCode}, selected) {
          onItemSelect(processCode, selected);
        },
        selectedRowKeys: listSelectedKeys,
      };

      return (
        <Table
          rowKey={'processCode'}
          rowSelection={rowSelection}
          columns={columns}
          pagination={false}
          dataSource={filteredItems}
          size="small"
          style={{pointerEvents: listDisabled ? 'none' : null}}
          onRow={({processCode, disabled: itemDisabled}) => ({
            onClick: () => {
              if (itemDisabled || listDisabled) return;
              onItemSelect(processCode, !listSelectedKeys.includes(processCode));
            },
          })}
        />
      );
    }}
  </Transfer>
);

const mockData = [
  {
    processCode: 'PRO0001',
    processName: '开料',
    processType: '主工艺',
  },
  {
    processName: '图形电镀',
    processType: '主工艺',
    processCode: 'PRO0002',
  },
  {
    processName: '喷锡',
    processType: '主工艺',
    processCode: 'PRO0003',
  },
  {
    processName: '成形',
    processType: '主工艺',
    processCode: 'PRO0004',
  },
  {
    processName: '测试',
    processType: '主工艺',
    processCode: 'PRO0005',
  },
  {
    processName: 'FQC',
    processType: '主工艺',
    processCode: 'PRO0006',
  },
  {
    processName: '检测',
    processType: '检测工艺',
    processCode: 'PRO0007',
  },
  {
    processName: '入库',
    processType: '其他',
    processCode: 'PRO0008',
  },
  {
    processName: '内层线路',
    processType: '主工艺',
    processCode: 'PRO0009',
  },
  {
    processName: '内层检验',
    processType: '检测工艺',
    processCode: 'PRO0010',
  },
  {
    processName: '层压',
    processType: '其他',
    processCode: 'PRO0011',
  },
  {
    processName: '沉铜板电',
    processType: '其他',
    processCode: 'PRO0012',
  }
]

const originTargetKeys = mockData.filter(item => +item.processCode % 3 > 1).map(item => item.processCode);


const {Option} = Select;
const {RangePicker} = DatePicker;
const fieldLabels = {
  materialCode: {
    label: '仓库编码',
    code: 'materialCode',
  },
  materialName: {
    label: '仓库名称',
    code: 'materialName',
  },
  remark: {
    label: '备注',
    code: 'remark',
  },
};

const tableData = [
  {
    materialCode: 'A0001',
    materialName: '物料1',
    supplier: 'A供应商',
    num: '60',
  },
  {
    materialCode: 'A0002',
    materialName: '物料2',
    supplier: 'B供应商',
    num: '90',
  },
  {
    materialCode: 'A0003',
    materialName: '物料3',
    supplier: 'C供应商',
    num: '100',
  },
]

const StockMaterialForm = (props, {submitting, dispatch}) => {
  const {visible} = props;
  const {TextArea} = Input;
  const {Step} = Steps;
  const [form] = Form.useForm();
  const [error, setError] = useState([]);
  const [isProcessModalVisible, setIsProcessModalVisible] = useState(false);
  const [targetKeys, setTargetKeys] = useState(originTargetKeys);
  const [targetData, setTargetData] = useState([]);

  const getErrorInfo = (errors) => {
    const errorCount = errors.filter((item) => item.errors.length > 0).length;

    if (!errors || errorCount === 0) {
      return null;
    }

    const scrollToField = (fieldKey) => {
      const labelNode = document.querySelector(`label[for="${fieldKey}"]`);

      if (labelNode) {
        labelNode.scrollIntoView(true);
      }
    };

    const errorList = errors.map((err) => {
      if (!err || err.errors.length === 0) {
        return null;
      }

      const key = err.name[0];
      return (
        <li key={key} className={styles.errorListItem} onClick={() => scrollToField(key)}>
          <CloseCircleOutlined className={styles.errorIcon}/>
          <div className={styles.errorMessage}>{err.errors[0]}</div>
          <div className={styles.errorField}>{fieldLabels[key]}</div>
        </li>
      );
    });
    return (
      <span className={styles.errorIcon}>
        <Popover
          title="表单校验信息"
          content={errorList}
          overlayClassName={styles.errorPopover}
          trigger="click"
          getPopupContainer={(trigger) => {
            if (trigger && trigger.parentNode) {
              return trigger.parentNode;
            }

            return trigger;
          }}
        >
          <CloseCircleOutlined/>
        </Popover>
        {errorCount}
      </span>
    );
  };

  const onFinish = (values) => {
    setError([]);
    dispatch({
      type: 'productForm/submitAdvancedForm',
      payload: values,
    });
  };

  const onFinishFailed = (errorInfo) => {
    setError(errorInfo.errorFields);
  };

  const onChange = (nextTargetKeys) => {
    setTargetKeys(nextTargetKeys)
    //console.log((nextTargetKeys)
    const targetDatas = mockData.filter((item)=>{
      let isExist;
      for (let key of nextTargetKeys) {
        if (item.processCode === key) {
          isExist = true;
          break;
        }
      }
      return isExist
    })
    setTargetData(targetDatas)
  }

  const handleProcessOk = ()=>{
    setIsProcessModalVisible(false);
  }

  const handleProcessCancel = ()=>{
    setIsProcessModalVisible(false);
  }

  return (
    <div className={'product-form'} style={{display: visible ? 'block' : 'none'}}>
      <Form
        form={form}
        layout="vertical"
        initialValues={{
          material: tableData,
        }}
        hideRequiredMark
        onFinish={onFinish}
        onFinishFailed={onFinishFailed}
      >
        <>
          <Card title="基本信息" className={styles.card} bordered={false}>
            <Row gutter={16}>
              <Col lg={8} md={12} sm={24}>
                <Form.Item
                  label={fieldLabels.materialName.label}
                  name={fieldLabels.materialName.code}
                  rules={[
                    {
                      required: true,
                      message: `请输入${fieldLabels.materialName.label}`,
                    },
                  ]}
                >
                <Select>
                  <Option value={1}>A仓库</Option>
                  <Option value={2}>B仓库</Option>
                  <Option value={3}>C仓库</Option>
                  <Option value={4}>D仓库</Option>
                </Select>
                </Form.Item>
              </Col>
              <Col lg={8} md={12} sm={24}>
                <Form.Item
                  label={fieldLabels.materialCode.label}
                  name={fieldLabels.materialCode.code}
                  rules={[
                    {
                      required: true,
                      message: `请输入${fieldLabels.materialCode.label}`,
                    },
                  ]}
                >
                  <Input placeholder={`请输入${fieldLabels.materialCode.label}`} disabled={true}/>
                </Form.Item>
              </Col>
            </Row>
            <Row gutter={16}>
              <Col lg={8} md={12} sm={24}>
                <Form.Item
                  label={fieldLabels.remark.label}
                  name={fieldLabels.remark.code}
                  rules={[
                    {
                      required: true,
                      message: `请输入${fieldLabels.remark.label}`,
                    },
                  ]}
                >
                  <TextArea placeholder={`请输入${fieldLabels.remark.label}`}/>
                </Form.Item>
              </Col>
            </Row>
          </Card>
          <Card title="选择物料" bordered={false}>
            <Form.Item name="material">
              <TableForm />
            </Form.Item>
          </Card>
        </>
        <FooterToolbar>
          {getErrorInfo(error)}
          <Button type="primary" onClick={props.onCancel.bind(this, false)}>
            返回
          </Button>
          <Button type="primary" onClick={() => form?.submit()} loading={submitting}>
            提交
          </Button>
        </FooterToolbar>
      </Form>
    </div>
  );
};

// export default connect(({ loading }) => ({
//   submitting: loading.effects['productForm/submitAdvancedForm'],
// }))(ProductForm);
export default StockMaterialForm;
